import React, { useState, useEffect } from 'react';
import { Layout, Card, Tabs, Form, Input, Select, Button, Table, Tag, Space, Typography, Avatar, Badge, Modal, message } from 'antd';
import { CheckCircleOutlined, IeOutlined, IdcardOutlined } from '@ant-design/icons';
import './ProfileSettingPage.css';

const { Header, Content } = Layout;
const { Title, Text, Link } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;

// 模拟用户基础信息数据
const userBasicInfo = {
  username: '张三',
  accountId: 'adminadmin',
  registerTime: '2025-07-14',
  realNameAuth: '已认证',
  phoneNumber: '15931788562',
  email: '',
  nickname: '',
  country: '',
  region: '',
  address: '',
  bio: ''
};

// 模拟安全设置数据
const securitySettings = {
  password: '已设置',
  passwordDesc: '密码至少6位字符，支持数字、字母和除空格外的特殊字符，且必须同时包含数字和大小写字母。',
  securityQuestion: '未设置',
  phone: '已绑定: 150*******50',
  email: '未设置'
};

// 模拟实名认证数据
const realNameAuthInfo = {
  accountType: '企业账号',
  status: '已认证',
  authTime: '2018-10-06',
  legalPerson: '李**',
  idType: '中国身份证',
  idNumber: '131****3246',
  companyName: '湖南****有限公司',
  companyDocType: '企业营业执照',
  orgCode: '5*****9',
  authRecords: [
    { id: '232', content: '每日推荐视频集', status: '审核中', createTime: '2021-02-28 10:30' },
    { id: '254', content: '每日推荐视频集', status: '已通过', createTime: '2021-02-28 10:30' }
  ]
};

// 认证状态标签组件
const StatusTag = ({ status }: { status: string }) => {
  if (status === '已认证' || status === '已通过') {
    return <Tag color="success"><CheckCircleOutlined /> {status}</Tag>;
  } else if (status === '审核中') {
    return <Tag color="processing">{status}</Tag>;
  } else {
    return <Tag>{status}</Tag>;
  }
};

// 认证记录表格列定义
const authRecordColumns = [
  { title: '认证类型', dataIndex: 'id', key: 'id' },
  { title: '认证内容', dataIndex: 'content', key: 'content' },
  { title: '当前状态', dataIndex: 'status', key: 'status', render: (status: string) => <StatusTag status={status} /> },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
  {
    title: '操作',
    key: 'action',
    render: (_: any, record: { id: string; content: string; status: string; createTime: string }) => (
      <Space size="small">
        <Link>查看</Link>
        {record.status === '审核中' && <Link>撤回</Link>}
      </Space>
    )
  }
];

const ProfileSettingPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [showPwdModal, setShowPwdModal] = useState(false);
  const [oldPwd, setOldPwd] = useState('');
  const [newPwd, setNewPwd] = useState('');
  const [confirmPwd, setConfirmPwd] = useState('');
  const [pwdLoading, setPwdLoading] = useState(false);

  // 密码格式校验
  const isValidPassword = (pwd: string) => /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+]{8,20}$/.test(pwd);

  const handlePwdChange = async () => {
    if (!oldPwd || !newPwd || !confirmPwd) {
      message.error('请填写所有字段');
      return;
    }
    if (!isValidPassword(newPwd)) {
      message.error('新密码格式不正确，需8-20位且包含字母和数字');
      return;
    }
    if (newPwd !== confirmPwd) {
      message.error('两次输入的新密码不一致');
      return;
    }
    setPwdLoading(true);
    // 这里应调用后端API进行密码修改
    setTimeout(() => {
      setPwdLoading(false);
      setShowPwdModal(false);
      setOldPwd(''); setNewPwd(''); setConfirmPwd('');
      message.success('密码修改成功！');
    }, 1000);
  };

  // 初始化表单数据
  useEffect(() => {
    const saved = localStorage.getItem('profile_basic_info');
    if (saved) {
      form.setFieldsValue(JSON.parse(saved));
    }
  }, [form]);

  // 表单提交处理
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      // 保存到localStorage
      localStorage.setItem('profile_basic_info', JSON.stringify(values));
      console.log('表单提交:', values);
      // 这里可以添加API调用保存数据
      setTimeout(() => {
        setLoading(false);
        // 显示成功提示
        message.success('保存成功');
      }, 1000);
    } catch (error) {
      setLoading(false);
      console.error('表单验证失败:', error);
    }
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
  };

  return (
    <Layout className="profile-setting-layout">
      <Header className="profile-header" style={{ background: '#fff', padding: '0 24px' }}>
        <Title level={2} style={{ margin: '16px 0' }}>个人中心 / 用户设置</Title>
      </Header>
      <Content className="profile-content" style={{ padding: '24px' }}>
        <Card className="profile-card">
          <div className="user-info-header">
            <div className="avatar-container">
              <Badge count={1} dot>
                <Avatar size={100} src="https://miaobi-lite.bj.bcebos.com/miaobi/5mao/b%276Jyh56yU5bCP5paw5oOF5L6j5aS05YOPXzE3Mjg5NDgyODguMjQ1MjcyMg%3D%3D%27/0.png" icon={<IdcardOutlined />} />
              </Badge>
            </div>
            <div className="user-basic-info">
              <Space direction="vertical" size="large">
                <div className="info-row">
                  <Text strong>用户名:</Text>
                  <Text style={{ marginLeft: 8 }}>{userBasicInfo.username}</Text>
                </div>
                <div className="info-row">
                  <Text strong>账号ID:</Text>
                  <Text style={{ marginLeft: 8 }}>{userBasicInfo.accountId}</Text>
                </div>
                <div className="info-row">
                  <Text strong>注册时间:</Text>
                  <Text style={{ marginLeft: 8 }}>{userBasicInfo.registerTime}</Text>
                </div>
                <div className="info-row">
                  <Text strong>实名认证:</Text>
                  <StatusTag status={userBasicInfo.realNameAuth} />
                  <Link style={{ marginLeft: 8 }}>修改</Link>
                </div>
                <div className="info-row">
                  <Text strong>手机号码:</Text>
                  <Text style={{ marginLeft: 8 }}>{userBasicInfo.phoneNumber}</Text>
                  <Link style={{ marginLeft: 8 }}>修改</Link>
                </div>
              </Space>
            </div>
          </div>

          <Tabs defaultActiveKey="basic" className="setting-tabs" style={{ marginTop: 24 }}>
            {/* 基础信息标签页 */}
            <TabPane tab={<><IdcardOutlined /> 基础信息</>} key="basic">
              <Form
                form={form}
                layout="vertical"
                className="basic-info-form"
              >
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}
                >
                  <Input placeholder="请输入邮箱" suffix={<span style={{ color: '#f50' }}>*</span>} />
                </Form.Item>

                <Form.Item
                  name="nickname"
                  label="昵称"
                >
                  <Input placeholder="请输入昵称" suffix={<span style={{ color: '#f50' }}>*</span>} />
                </Form.Item>

                <Form.Item
                  name="country"
                  label="国家/地区"
                >
                  <Select placeholder="请选择">
                    <Option value="china">中国</Option>
                    <Option value="usa">美国</Option>
                    <Option value="japan">日本</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  name="region"
                  label="所在区域"
                >
                  <Select placeholder="请选择">
                    <Option value="beijing">北京</Option>
                    <Option value="shanghai">上海</Option>
                    <Option value="guangzhou">广州</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  name="address"
                  label="具体地址"
                >
                  <Input placeholder="请输入具体地址" />
                </Form.Item>

                <Form.Item
                  name="bio"
                  label="个人简介"
                >
                  <TextArea rows={4} placeholder="请输入个人简介" />
                </Form.Item>

                <Form.Item>
                  <Space>
                    <Button type="primary" onClick={handleSubmit} loading={loading}>保存</Button>
                    <Button onClick={handleReset}>重置</Button>
                  </Space>
                </Form.Item>
              </Form>
            </TabPane>

            {/* 安全设置标签页 */}
            <TabPane tab={<><IeOutlined /> 安全设置</>} key="security">
              <div className="security-setting-item">
                <div className="setting-label">登录密码</div>
                <div className="setting-content">
                  <div className="setting-value">{securitySettings.password}</div>
                  <div className="setting-desc">{securitySettings.passwordDesc}</div>
                  <Link className="setting-action" onClick={() => setShowPwdModal(true)}>修改</Link>
                </div>
              </div>

              <div className="security-setting-item">
                <div className="setting-label">密保问题</div>
                <div className="setting-content">
                  <div className="setting-value">{securitySettings.securityQuestion}</div>
                  <div className="setting-desc">密保问题可以有效的保护账号的安全。</div>
                  <Link className="setting-action">设置</Link>
                </div>
              </div>

              <div className="security-setting-item">
                <div className="setting-label">安全手机</div>
                <div className="setting-content">
                  <div className="setting-value">{securitySettings.phone}</div>
                  <Link className="setting-action">修改</Link>
                </div>
              </div>

              <div className="security-setting-item">
                <div className="setting-label">安全邮箱</div>
                <div className="setting-content">
                  <div className="setting-value">{securitySettings.email}</div>
                  <div className="setting-desc">绑定邮箱可以用来找回密码、接收通知等。</div>
                  <Link className="setting-action">设置</Link>
                </div>
              </div>
            </TabPane>

            {/* 实名认证标签页 */}
            <TabPane tab={<><IdcardOutlined /> 实名认证</>} key="realname">
              <div className="auth-section">
                <Title level={5}>企业实名认证</Title>
                <div className="auth-info-card">
                  <div className="auth-info-row">
                    <div className="auth-info-label">账号类型:</div>
                    <div className="auth-info-value">{realNameAuthInfo.accountType}</div>

                    <div className="auth-info-label">认证状态:</div>
                    <div className="auth-info-value"><StatusTag status={realNameAuthInfo.status} /></div>

                    <div className="auth-info-label">认证时间:</div>
                    <div className="auth-info-value">{realNameAuthInfo.authTime}</div>
                  </div>

                  <div className="auth-info-row">
                    <div className="auth-info-label">法人姓名:</div>
                    <div className="auth-info-value">{realNameAuthInfo.legalPerson}</div>

                    <div className="auth-info-label">法人证件类型:</div>
                    <div className="auth-info-value">{realNameAuthInfo.idType}</div>

                    <div className="auth-info-label">法人认证号码:</div>
                    <div className="auth-info-value">{realNameAuthInfo.idNumber}</div>
                  </div>

                  <div className="auth-info-row">
                    <div className="auth-info-label">企业名称:</div>
                    <div className="auth-info-value">{realNameAuthInfo.companyName}</div>

                    <div className="auth-info-label">企业证件类型:</div>
                    <div className="auth-info-value">{realNameAuthInfo.companyDocType}</div>

                    <div className="auth-info-label">组织机构代码:</div>
                    <div className="auth-info-value">{realNameAuthInfo.orgCode}</div>
                  </div>
                </div>
                <Link className="modify-auth-action">修改认证主体</Link>
              </div>

              <div className="auth-section">
                <Title level={5}>认证记录</Title>
                <Table
                  columns={authRecordColumns}
                  dataSource={realNameAuthInfo.authRecords}
                  pagination={{
                    pageSize: 5,
                    showSizeChanger: false,
                    showTotal: (total) => `共${total}条`
                  }}
                  rowKey="id"
                />
              </div>
            </TabPane>
          </Tabs>
        </Card>
      </Content>
      {/* 修改密码弹窗 */}
      <Modal
        open={showPwdModal}
        title="修改密码"
        onCancel={() => setShowPwdModal(false)}
        onOk={handlePwdChange}
        confirmLoading={pwdLoading}
        okText="保存"
        cancelText="取消"
      >
        <div style={{ maxWidth: 400, margin: '0 auto' }}>
          <div style={{ marginBottom: 16 }}>
            <Input.Password
              placeholder="请输入原密码"
              value={oldPwd}
              onChange={e => setOldPwd(e.target.value)}
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <Input.Password
              placeholder="请输入新密码"
              value={newPwd}
              onChange={e => setNewPwd(e.target.value)}
            />
          </div>
          <div style={{ marginBottom: 0 }}>
            <Input.Password
              placeholder="请确认新密码"
              value={confirmPwd}
              onChange={e => setConfirmPwd(e.target.value)}
            />
          </div>
        </div>
      </Modal>
    </Layout>
  );
};

export default ProfileSettingPage;